package com.yzycoc.hamster.demo.time202505.time20250528.test;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class GetIp {


    /**
     * 获取外网IP
     */
    public static String getNetworkIp() {
        String networkIp = getIpFromUrl("https://qifu-api.baidubce.com/ip/local/geo/v1/district", "ip");
        if (isValidIPAddress(networkIp)) return networkIp;

        networkIp = getIpFromUrl("https://www.ipplus360.com/getIP", "data");
        if (isValidIPAddress(networkIp)) return networkIp;

        networkIp = getIpFromUrl("https://www.ip.cn/api/index?ip&type=0", "ip");
        if (isValidIPAddress(networkIp)) return networkIp;

        networkIp = getIpFromUrl("https://ip.useragentinfo.com/json", "ip");
        if (isValidIPAddress(networkIp)) return networkIp;

        throw new RuntimeException("无法初始化，无法获取外网IP，请联系作者修复！");
    }

    /**
     * 根据 URL 获取指定字段的 IP 地址，并打印日志
     */
    private static String getIpFromUrl(String url, String key) {
        try {
            String response = HttpUtil.get(url, 3000); // 超时时间 3 秒
            JSONObject json = JSON.parseObject(response);
            String ip = json.getString(key);
            if (isValidIPAddress(ip)) {
                log.info("通过接口 [{}] 获取外网IP成功，字段 [{}]，IP为：{}", url, key, ip);
            } else {
                log.warn("接口 [{}] 返回数据中字段 [{}] 无效：{}", url, key, ip);
            }
            return ip;
        } catch (Exception e) {
            log.error("请求接口 [{}] 出现异常：{}", url, e.getMessage());
            return null;
        }
    }


    /**
     * IP 校验方法，可根据需要自行完善
     */
    private static boolean isValidIPAddress(String ip) {
        if (ip == null || ip.isEmpty()) return false;
        return ip.matches("((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)");
    }
}
